#ifndef _GWBASE_BASE_THREAD_H_
#define _GWBASE_BASE_THREAD_H_

#include <pthread.h>
#include <string>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>

namespace dicom {

extern pid_t gettid();

// Thread object and pthread instance is loosely connected, that is,
// you can delete Thread object before the actual pthread terminates.
class Thread: public boost::noncopyable {
 public:
  typedef boost::function<void()> ThreadFunc;

  Thread(const ThreadFunc& func, const std::string& name);
  ~Thread();

  // Thread can be started only once, when it is terminated, 
  // you can _not_ restart it
  void Start();

  // wait for thread termination, and return the exit code
  int Join();

  pid_t pid() const { return *tid_; }

 private:
  ThreadFunc func_;
  std::string name_;
  pthread_t pthread_;
  boost::shared_ptr<pid_t> tid_;
  bool started_;
  bool joined_;
};

typedef boost::shared_ptr<Thread> ThreadPtr;

}

#endif /* _GWBASE_BASE_THREAD_H_ */
